<template>
  <div class="roleList">
    <a-card :bordered="false" :style="{ height: '100%' }">
      <a-row :gutter="24">
        <a-col :md="4">
          <a-list itemLayout="vertical" :dataSource="roles">
            <a-list-item slot="renderItem" slot-scope="item, index" :key="index">
              <a-list-item-meta :style="{ marginBottom: '0' }">
                <span slot="description" style="text-align: center; display: block">{{ item.key }}</span>
                <a slot="title" style="text-align: center; display: block" @click="edit(item)">{{ item.role_name }}</a>
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </a-col>
        <a-col :md="20">
          <div style="max-width: 1000px">
            <div v-if="form.id">
              <h3>角色：{{ form.role_name }}</h3>
            </div>
            <a-divider />
            <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" @submit="handleSubmit">
              <a-form-model-item label="角色名称">
                <a-input v-model="form.role_name" />
              </a-form-model-item>
              <a-form-model-item label="唯一键">
                <a-input v-model="form.key" />
              </a-form-model-item>
              <a-form-model-item label="拥有权限">
                <a-row :gutter="24">
                  <a-col
                    style=" display: flex;justify-content: flex-start;align-items: center;"
                    :lg="24"
                    :md="24"
                    :sm="24">
                    <div>
                      <div v-for="(item,index) in loadData" :key="item.id">
                        <a-checkbox
                          :indeterminate="item.indeterminate"
                          :checked="item.checkedAll"
                          :value="item.checkedAll"
                          @change="onChangeCheckAll($event, item,item.id,index)">全选
                        </a-checkbox>
                        <a-checkbox-group
                          style="margin-left:20px"
                          v-model="item.selected"
                          @change="onChangeCheck($event,item)">
                          <a-checkbox
                            v-for="child in item.children"
                            :key="child.id"
                            @change="clickChenck($event, item,index)"
                            :value="child.id">{{ child.name }}
                          </a-checkbox>
                        </a-checkbox-group>
                      </div>
                    </div>
                  </a-col>
                </a-row>
              </a-form-model-item>
              <a-form-model-item label="tips">
                <span style="color:red">第一项为父权限,同行剩余为子权限,如选择子权限请一并勾选第一项父权限!</span>
              </a-form-model-item>
              <a-form-model-item label="">
                <div style="margin-left:125px">
                  <div v-if="form.id==='-1'|| form.id===undefined">
                    <a-button type="primary" html-type="submit">提交</a-button>
                  </div>
                  <div v-else>
                    <a-button type="primary" @click="doEdit">保存</a-button>
                    <a-popconfirm placement="top" okText="确定" cancelText="取消" @confirm="delRole(form.id)">
                      <template slot="title">
                        确认删除吗?
                      </template>
                      <a-button style="margin-left:20px" type="danger">删除</a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </a-form-model-item>
            </a-form-model>

          </div>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {
    getRoleList,
    doAddRole,
    getPermsList,
    doEditRole,
    delRole
  } from '@/api/permission'
  // import { getRoleList } from '@/api/local/permission'
  import {
    baseMixin
  } from '@/store/app-mixin'
  //   import pick from 'lodash.pick'

  export default {
    name: 'RoleList',
    mixins: [baseMixin],
    components: {},
    data () {
      return {
        labelCol: {
          span: 3
        },
        wrapperCol: {
          span: 15
        },
        checkedList: [],
        indeterminate: true,
        checkAll: false,
        plainOptions: [],
        form: {
          id: '-1',
          role_name: '',
          key: ''
        },
        mdl: {},
        loadData: [],
        roles: [{
          id: '-1',
          role_name: '新增角色',
          key: '新增一个角色'
        }],
        valuses: {},
        // permisNameList: [],
        chList: [],
        permischeck: [],
        a: [],
        b: [],
        tem: [],
        checkedRole: [],
        c: [],
        d: []
      }
    },
    created () {
      //   this.getPermsList()
      this.getRoleList()
    },
    methods: {
      clickChenck (e, item, index) {
        // console.log('框', e, item, index)
        event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true
        // console.log('e.target.value', e.target.value)
        // 选中
        if (e.target.checked === true) {
          if (this.checkedList.includes(e.target.value)) {} else {
            this.checkedList.push(e.target.value)
          }
        }
        // 取消选中
        if (e.target.checked === false) {
          const tarindex = this.checkedList.indexOf(e.target.value)
          this.checkedList.splice(tarindex, 1)
        }
        Vue.set(this.loadData, index, item)
        // console.log('this.checkedList', this.checkedList)
      },
      // 多选组
      onChangeCheck (e, item) {
        // console.log('多选组', e, item)
        item.indeterminate = !!item.selected.length && (item.selected.length < item.children.length)
        item.checkedAll = item.selected.length === item.children.length
      },
      // 全选
      onChangeCheckAll (e, item, id, index) {
        // console.log('全选', e, item, id, index)
        Object.assign(item, {
          selected: e.target.checked ? item.children.map(obj => obj.id) : [],
          indeterminate: false,
          checkedAll: e.target.checked
        })
        Vue.set(this.loadData, index, item)
        this.tem.push(...item.selected)
        // console.log('this.tem', this.tem)
        // 取消选中
        if (e.target.checked === false) {
          this.checkFalse(id)
        }
        // 全选中
        if (e.target.checked === true) {
          for (let h = 0; h < this.tem.length; h++) {
            if (this.checkedList.indexOf(this.tem[h]) !== -1) {} else {
              this.checkedList.push(this.tem[h])
            }
          }
        }
        this.tem = []
        // console.log('this.checkedList', this.checkedList)
      },
      checkFalse (id) {
        const obj = this.loadData.filter(e => e.id === id)
        this.obj1 = obj[0].actions
        // console.log(this.obj1)
        this.obj1.forEach((item, index, array) => {
          this.checkedList.splice(this.checkedList.indexOf(item), 1)
        })
        this.tem = []
        // console.log('取消点击')
      },
      doEdit () {
        // this.values.role_name = this.form.id
        // console.log('修改表单', this.form)
        if (this.form.role_name !== '' && this.form.key !== '') {
          // this.form.auth = this.form.selected.toString()
          // console.log('auth', this.form.auth)
          this.doEditRole(this.form)
        } else {
          this.$message.info('请检查表单!')
        }
      },
      doEditRole (values) {
        doEditRole({
          role_id: values.id,
          role_name: values.role_name,
          key: values.key,
          auth: values.selected.toString()
        }).then((res) => {
          if (res.code === 200) {
            console.log(res)
            this.$message.success('修改成功!')
            this.getPermsList()
            this.form = {}
            this.checkedList = []
          } else {
            this.$message.info(res.msg)
          }
        }).catch(err => {
          this.$message.error('修改失败!')
          console.log(err)
        })
      },
      delRole (id) {
        // console.log(this.form)
        delRole({
          role_id: id
        }).then((res) => {
          // console.log('删除返回',res)
          this.$message.success('删除成功!')
          this.getPermsList()
          this.getRoleList()
          this.form = {}
          this.checkedList = []
        }).catch(err => {
          console.log(err)
          this.$message.error('删除失败!')
        })
      },
      getRoleList () {
        this.roles = [{
          id: '-1',
          role_name: '新增角色',
          key: '新增一个角色'
        }]
        getRoleList({
          page: 1,
          pagesize: 999999
        }).then((res) => {
          // console.log('角色列表', res)
          //   this.roles.push(...res.data.data)
          // this.roles = res.result
          const temp = res.data.data.map(function (obj) {
            var rObj = {}
            rObj.id = obj.id
            rObj.role_name = obj.role_name
            rObj.key = obj.key
            rObj.selected = obj.auth.split(',').map(Number)
            return rObj
          })
          // console.log('temp', temp)
          this.roles.push(...temp)
          // console.log('this.roles', this.roles)
          this.getPermsList()
        }).catch(err => {
          console.log(err)
        })
      },
      handleSubmit (e) {
        e.preventDefault()
          if (this.form.role_name !== '' && this.form.key !== '') {
            // this.form.rlPermsList = this.checkedList
          // console.log('form: ', values)
          this.doAddRole(this.form)
        }
      },

      getPermsList () {
        getPermsList({
          page: 1,
          pagesize: 9999
        }).then(res => {
          // console.log('权限列表', res)
          this.loadData = res.data.data
          this.a = []
          this.b = []
          for (const i in this.loadData) {
            this.loadData[i].checkedAll = false
            this.loadData[i].actions = []
            this.loadData[i].children = []
            this.loadData[i].children.push(this.loadData[i])
            this.loadData[i].children.push(...this.loadData[i].data)
            for (const c in this.loadData[i].children) {
              this.loadData[i].actions.push(this.loadData[i].children[c].id)
            }
          }

          // console.log('loadData', this.loadData)
        }).catch(err => {
          console.log(err)
          this.loading = false
        })
      },
      doAddRole (value) {
        // console.log('value', value)
        doAddRole({
          role_name: value.role_name,
          key: value.key,
          auth: this.checkedList.toString()
        }).then(res => {
          // console.log('新增返回', res)
          this.$message.success('添加成功!')
          this.getRoleList()
          this.getPermsList()
          this.form = {}
          this.checkedList = []
        }).catch(err => {
          console.log(err)
          this.$message.error('添加失败!')
        })
      },
      eval (fn) {
        // 数组字符串转数组
        var Fn = Function // 一个变量指向Function，防止有些前端编译工具报错
        return new Fn('return ' + fn)()
      },
      edit (record) {
        // console.log('editrecord', record)
        this.form = record
        // this.loadData.selected = record.selected
        // console.log(' this.loadData', this.loadData)
        if (this.form.id === -1) {
          this.form.role_name = ''
          this.form.key = ''
        }
        for (let c = 0; c < this.loadData.length; c++) {
          this.loadData[c].selected = []
          this.loadData[c].checkedAll = false
          this.loadData[c].indeterminate = false
        }
        if (record.id === '-1') {
          this.form = {}
          this.checkedList = []
        } else {
          record.selected.forEach((item, index, array) => {
            for (let a = 0; a < this.loadData.length; a++) {
              if (this.loadData[a].actions.includes(item)) {
                this.loadData[a].selected.push(item)
              }
              // }
              if (this.loadData[a].selected.length === 0) {
                this.loadData[a].checkedAll = false
                this.loadData[a].indeterminate = false
              } else if (this.loadData[a].selected.length < this.loadData[a].actions.length) {
                this.loadData[a].checkedAll = false
                this.loadData[a].indeterminate = true
              } else if (this.loadData[a].selected.length === this.loadData[a].actions.length) {
                this.loadData[a].checkedAll = true
                this.loadData[a].indeterminate = false
              }
            }
          })
          this.checkedList = record.selected
          // console.log('this.loadData', this.loadData)
          // console.log('this.checkedList', this.checkedList)
        }
      }
    }
  }
</script>

<style scoped>

</style>
